<template>
  <div v-loading="loading" class="dashboard-container">
    <div class="app-container">
      <el-card class="tree-card">
        <tree-tools :treeNode="company" :isRoot="true" @addDepts="addDepts" />
        <!-- 放置一个 el-tree -->
        <el-tree
          :data="departs"
          :props="defaultProps"
          :default-expand-all="true"
        >
          <!-- @delDepts="getDepartments" 把获取数据方法传递给子组件 -->
          <tree-tools
            slot-scope="{ data }"
            :treeNode="data"
            @delDepts="getDepartments"
            @addDepts="addDepts"
            @editDepts="editDepts"
          />
        </el-tree>
      </el-card>
    </div>
    <!-- 放置新增弹层 -->
    <add-dept
      ref="addDept"
      :showDialog.sync="showDialog"
      :treeNode="node"
      @addDepts="getDepartments"
    />
  </div>
</template>

<script>
import TreeTools from "@/views/departments/components/tree-tools.vue";
import AddDept from "@/views/departments/components/add-dept.vue";
import { getDepartments } from "@/api/departments";
import { tranListToTreeData } from "@/utils/index";
export default {
  components: { TreeTools, AddDept },
  created() {
    this.getDepartments();
  },
  data() {
    return {
      // 结构
      departs: [],
      defaultProps: {
        // 指定渲染的别名
        // 默认 label
        label: "name",
      },
      // 标题
      company: {},
      // 模态框状态
      showDialog: false,
      // 记录当前的部门
      node: null,
      loading: true,
    };
  },
  methods: {
    async getDepartments() {
      const result = await getDepartments();
      this.company = { name: result.companyName, manager: "负责人", id: "" };
      // 因为查找父节点的 pid 要等于空，传递一个空
      this.departs = tranListToTreeData(result.depts, "");
      this.loading = false;
    },
    // 添加
    addDepts(val) {
      this.showDialog = true;
      // 把当前要添加的部门记录下来
      this.node = val;
    },
    // 编辑
    editDepts(val) {
      this.showDialog = true;
      this.node = val;
      // 把对应结构的 id 传递过去
      this.$refs.addDept.getDepartDetail(val.id);
    },
  },
};
</script>

<style scoped>
.tree-card {
  padding: 30px 140px;
  font-size: 14px;
}
</style>
